package com.bo.datasource;

import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;

@Configuration // 该注解类似于spring配置文件
@MapperScan(basePackages = "com.bo.dao")
public class MyBatisConfig {
	/**
	 * 配置数据源
	 * @Primary 必需指定一个且只能有一个主数据源，否则报错 当有多个实现类型时，注解了@Primary则优先使用
     */
    @Primary 
	@Bean(name = "miya_shop") //此处指向yml配置文件中具体的数据源
	@ConfigurationProperties(prefix = "spring.datasource.miya_shop")
	public DataSource dbMiyaShop() {
		return DruidDataSourceBuilder.create().build();
	}
	@Bean
	@ConfigurationProperties(prefix = "spring.datasource.miya")
	public DataSource dbMiya() {
		return DruidDataSourceBuilder.create().build();
	}

	/**
	 * 核心动态数据源
	 *
	 * @return 数据源实例
	 */
	@Primary //当有多个实现类型时，注解了@Primary则优先使用
	@Bean
	public DataSource dynamicDataSource() {
		DynamicDataSource dataSource = new DynamicDataSource();
		dataSource.setDefaultTargetDataSource(dbMiyaShop());
		Map<Object, Object> dataSourceMap = new HashMap<Object, Object>();
		dataSourceMap.put(DataSourceType.miya_shop, dbMiyaShop());
		dataSourceMap.put(DataSourceType.miya, dbMiya());
		dataSource.setTargetDataSources(dataSourceMap);
		return dataSource;
	}

	@Bean
	public SqlSessionFactory sqlSessionFactory() throws Exception {
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		sqlSessionFactoryBean.setDataSource(dynamicDataSource());
		//配置对应的bean包名
		sqlSessionFactoryBean.setTypeAliasesPackage("com.bo.bean");
		//此处设置为了解决找不到mapper文件的问题
		sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
		return sqlSessionFactoryBean.getObject();
	}

	@Bean
	public SqlSessionTemplate sqlSessionTemplate() throws Exception {
		return new SqlSessionTemplate(sqlSessionFactory());
	}

	/**
	 * 事务管理
	 *
	 * @return 事务管理实例
	 */
	@Bean
	public PlatformTransactionManager platformTransactionManager() {
		return new DataSourceTransactionManager(dynamicDataSource());
	}

}
